#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import threading
from elasticsearch import Elasticsearch
import click
import logging


logging.getLogger().setLevel(logging.INFO)
queries = []
mutex = threading.Lock()


@click.command()
@click.option('--host', help='elasticsearch host address', default='http://127.0.0.1:9200/',  required=1)
def main(host):
    process_group_data(host)


def select_by_poc_none_value(es, fields=None, offset=0, limit=0):
    for record in es.search(index="centdb", doc_type="cent",
                            body={'query': {'match_all': {}}}, _source_include=fields or [],
                            from_=offset, size=limit
                            ).get('hits', {}).get('hits', []):
        yield record['_source']


def modify_poc_none_value(es, resultid, poc):
    ret = es.update(index="centdb", doc_type="cent",
                    body={'doc': {'poc': poc}}, id=resultid)
    return ret


def process_group_data(host):
    offset = 0
    limit = 20
    centes = Elasticsearch(hosts=host)
    while True:
        results = select_by_poc_none_value(centes, offset=offset, limit=limit)
        results = list(results)
        nmatched = len(results)
        if nmatched == 0:
            break
        offset += nmatched
        for result in results:
            if not result:
                continue
            resultid = result.get('resultid', '')
            poc = result.get('resultid', '')
            if poc == '' and resultid != '':
                logging.info("modify poc in resultid: %s" % (resultid))
                modify_poc_none_value(centes, resultid, None)

if __name__ == '__main__':
    main()

